// const { generateToken } = require('../utils/jwt')
const bcrypt = require('bcryptjs')
const User = require('../models/users')
const UserService = require('../services/users')
module.exports = {
  async register(req, res) {
    const { username, password } = req.body

    try {
      // 加密密码
      const hashedPassword = await bcrypt.hash(password, 10)
      const user = new User({ username, password: hashedPassword })
      await user.save()

      // res.send("User registered successfully");
      res.send({
        code: 200,
        msg: '注册成功'
      })
    } catch (error) {
      if (
        error.name === 'MongoServerError' &&
        error.errorResponse.code === 11000
      ) {
        return res.status(400).send({
          code: 11000,
          msg: '用户名已存在'
        })
      }
      res.status(500).send({
        code: 0,
        msg: '服务器请求失败'
      })
    }
  },
  async login(req, res) {
    try {
      const results = await UserService.login(req.body)
      if (results === 'User not found') {
        res.send({
          code: 11000,
          msg: '用户名不存在'
        })
      } else if (results === 'Invalid password') {
        res.send({
          code: 12000,
          msg: '密码错误'
        })
      } else {
        const { username, roles, avatar, introduction, token, createTime } =
          results
        res.send({
          code: 200,
          msg: {
            username,
            token,
            roles,
            avatar,
            introduction,
            createTime
          }
        })
      }
    } catch (error) {
      res.send({
        code: 0,
        msg: '服务器请求失败'
      })
    }
  },
  async getUsers(req, res) {
    try {
      const users = await User.find()
      res.send(users)
    } catch (error) {
      res.status(500).send({
        code: 0,
        msg: '服务器请求失败'
      })
    }
  },
  async getUsersById(req, res) {
    try {
      const user = await User.findById(req.params.id)
      res.send(user)
    } catch (error) {
      res.status(500).send({
        code: 0,
        msg: '不存在该用户'
      })
    }
  },
  async updateUsers(req, res) {
    try {
      await User.findByIdAndUpdate(req.params.id, req.body, {
        new: true
      })
      res.send({
        code: 200,
        msg: '更新成功'
      })
    } catch (error) {
      res.status(500).send({
        code: 0,
        msg: '服务器请求失败'
      })
    }
  },
  async deleteUsers(req, res) {
    try {
      await User.findByIdAndDelete(req.params.id)
      res.send({
        code: 200,
        msg: '删除成功'
      })
    } catch (error) {
      res.status(500).send({
        code: 0,
        msg: '服务器请求失败'
      })
    }
  }
}
